'use strict';
import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import SHA1 from 'crypto-js/sha1';
import Hex from 'crypto-js/enc-hex';
import { ApiTable } from '$utils'
import { Request } from '@peace/utils'
import { Button, Input, Form, Row, Col, message, Tabs } from 'antd';
import { login, LOGIN_ERROR } from '../actions/auth';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Uploads } from '$components'
import '../style.less';

const FormItem = Form.Item;

let codCountDownInterval = null
const Login = props => {
    const { dispatch, user, error, isRequesting } = props
    const [username, setUserName] = useState('')
    const [password, setPassword] = useState('')
    const [phone, setPhone] = useState('')
    const [code, setCode] = useState('')
    const [inputChanged, setInputChanged] = useState(false)
    const [curTabKey, setCurTabKey] = useState(1)
    const [codSending, setCodSending] = useState(false)
    const [codCountDown, setCodeCountDown] = useState(60)
    const codCountDownRef = useRef(0)

    useEffect(() => {
        sessionStorage.removeItem('user');
        localStorage.removeItem('governmentDataResourceCenter_selected_sider')
        localStorage.removeItem('governmentDataResourceCenter_open_sider')
    }, [])


    useEffect(() => {
        if (user && user.authorized) {
            user?.role == '数据消费者' ? dispatch(push('/metadataManagement/latestMetadata')) : dispatch(push('/homePage'));
        }
    }, [user])

    useEffect(() => {
        if (codSending) {
            setCodeCountDown(59)
            codCountDownRef.current = 59
            codCountDownInterval = setInterval(() => {
                codCountDownRef.current -= 1
                if (codCountDownRef.current == 0) {
                    setCodSending(false)
                    setCodeCountDown(60)
                    clearInterval(codCountDownInterval)
                    codCountDownInterval = null
                } else {
                    setCodeCountDown(codCountDownRef.current)
                }
            }, 1000);
        } else {
            if (codCountDownInterval) {
                clearInterval(codCountDownInterval)
                codCountDownInterval = null
                setCodeCountDown(60)
            }
        }
    }, [codSending])

    const doLogin = () => {
        if (curTabKey == 1) {
            if (!username || !password)
                dispatch({
                    type: LOGIN_ERROR,
                    payload: { error: '请输入账号名和密码' }
                });
            setInputChanged(false)
            dispatch(login({ username, password }));
        } else {
            if (!phone || !code)
                dispatch({
                    type: LOGIN_ERROR,
                    payload: { error: '请输入手机号和验证码' }
                });
            dispatch(login({ phone, code }));
        }
    }

    const enterHandler = e => {
        if (e.key === 'Enter') {
            doLogin()
        }
    };

    return (
        <div className='login'>
            <div className='left'></div>
            <div className='right'>
                <div className='loginBox'>
                    <div className='_title'>欢迎登录系统</div>
                    <div className='_divider'></div>
                    <Form onKeyDown={enterHandler}>

                        <FormItem>
                            <Input
                                style={{ marginTop: 30 }}
                                placeholder='请输入账号'
                                className='loginInp'
                                type="text"
                                value={username}
                                // maxlength={11}
                                onChange={e => {
                                    setUserName(e.target.value)
                                    setInputChanged(true)
                                }}
                            />
                        </FormItem>
                        <FormItem>
                            <Input
                                style={{ marginTop: 30 }}
                                placeholder='请输入密码'
                                className='loginInp'
                                type="password"
                                value={password}
                                onChange={e => {
                                    setPassword(e.target.value)
                                    setInputChanged(true)
                                }}
                            />
                        </FormItem>
                    </Form>
                    <Row style={{
                        paddingLeft: '10%'
                    }}>
                        {
                            inputChanged || !error ?
                                <span style={{
                                    visibility: 'hidden'
                                }}>-</span> :
                                <span>
                                    <ExclamationCircleOutlined style={{ color: 'red' }} />{error}
                                </span>
                        }
                    </Row>
                    <Button style={{ borderRadius: 28 }} type="primary" className='loginBtn' loading={isRequesting} onClick={doLogin}>登录</Button>
                </div>
            </div>
        </div>
    );
}

function mapStateToProps(state) {
    const { auth } = state;
    return {
        user: auth.user,
        error: auth.error,
        isRequesting: auth.isRequesting
    }
}

export default connect(mapStateToProps)(Login);